package com.huiquan.icd.service;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.ModelAndView;

import com.huiquan.analysis.domain.User;
import com.huiquan.framework.base.BaseService;
import com.huiquan.framework.base.ReturnCode;
import com.huiquan.framework.base.ReturnData;
import com.huiquan.framework.utils.GetListUtil;
import com.huiquan.framework.utils.ReturnUtil;
import com.huiquan.icd.dao.IcdDiseaseSymptomDescriptionDao;
import com.huiquan.icd.domain.IcdDiseaseSymptomDescription;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

@Service
public class IcdDiseaseSymptomDescriptionService extends BaseService {

	@Autowired
	private IcdDiseaseSymptomDescriptionDao icdDiseaseSymptomDescriptionDao;

	public ModelAndView list(Integer startStr, String keyword, String countPerPageStr, User user, String checkFlag,String exactSearchFlag) {
		boolean exactFlag = exactSearchFlag != null && exactSearchFlag.equals("1");

		Map<String, Object> param = new HashMap<>();
		param.put("checkFlag", checkFlag);
		if (keyword != null && !keyword.isEmpty()) {
			param.put("keyword", exactFlag ? keyword : "%" + keyword + "%");
		}
		int totalSize = icdDiseaseSymptomDescriptionDao.retrieveSize(param);
		Map<String, Integer> pageNo;
		if (countPerPageStr != null && !countPerPageStr.isEmpty()) {
			int countPerPage = Integer.parseInt(countPerPageStr);
			pageNo = GetListUtil.getPageNoParam(totalSize, startStr + "", countPerPage);
			param.put("countPerPage", countPerPage);
		} else {
			pageNo = GetListUtil.getPageNoParam(totalSize, startStr + "");
		}
		int endPage = pageNo.get("endPage");
		int start = pageNo.get("start");
		int startIndex = pageNo.get("startIndex");
		List<IcdDiseaseSymptomDescription> list = new ArrayList<>();

		if (startIndex < totalSize) {
			param.put("startIndex", startIndex);
			list = icdDiseaseSymptomDescriptionDao.retrieveList(param);
		}

		for (IcdDiseaseSymptomDescription value : list) {
			if (StringUtils.isNotBlank(value.getArray())) {
				String[] arrs = value.getArray().split((char) 1 + "");
				String[] parts = value.getPartPattern().split((char) 1 + "");
				String[] ids = value.getIds().split((char) 1 + "");

				List<Map<String, String>> arrList = new ArrayList<>();
				value.setDescription(value.getDescription().trim());
				for (int i = 0; i < arrs.length; i++) {
					Map<String, String> arrMap = new HashMap<>();
					arrMap.put("array", arrs[i]);
					arrMap.put("part_pattern", parts[i]);
					arrMap.put("id", ids[i]);
					arrList.add(arrMap);
				}
				value.setArrayList(arrList);
			}
		}

		Map<String, String> showSearch = new LinkedHashMap<>();
		showSearch.put("keyword", "疾病名称");

		Map<String, String> searchMap = new HashMap<>();
		searchMap.put("keyword", keyword);

		Map<String, Object> map = GetListUtil.getReturnMap2(totalSize, start, startIndex, endPage, list, searchMap);
		map.put("showSearch", showSearch);
		map.put("showSearchValue", searchMap);

		LOGGER.info("Get list end!Params:start={},wordKey={},propertyKey={},type={};total size={}",
				new Object[] { start, totalSize });
		return new ModelAndView("icd/index", map);
	}

	public ReturnData splitText(String id, String text, User user) throws Exception {
		if (StringUtils.isNotBlank(id) && StringUtils.isNotBlank(text)) {
			String array = "";
			String partPattern = "";

			// 调用分词接口
			JSONObject json = httpPost("http://172.16.0.181:1990/recognition", text);
			Map<String, String> rtn = getTextSplitWord(json);
			if (rtn != null) {
				array = rtn.get("arr");
				partPattern = rtn.get("part");
			}
			if (StringUtils.isNotBlank(array) && StringUtils.isNotBlank(partPattern)) {
				// 检查是否分词相同
				int count = icdDiseaseSymptomDescriptionDao.checkRepeat(array, partPattern, id,"");
				if (count > 0) {
					ReturnCode rc = ReturnCode.DYNAMIC_DESC_EXCEPTION;
					rc.setDesc("分词有重复");
					return ReturnUtil.fail(rc);
				}
				//
				IcdDiseaseSymptomDescription value = new IcdDiseaseSymptomDescription();
				value.setArray(array);
				value.setPartPattern(partPattern);
				value.setDescriptionId(Long.parseLong(id));
				value.setModifierId(user.getUserId() + "");
				icdDiseaseSymptomDescriptionDao.insert(value);
			}

		}

		return ReturnUtil.success();
	}

	public ReturnData submitPage(String id, User user) {
		if (StringUtils.isNotBlank(id)) {
			id = id.substring(0, id.length() - 1);
			// 校验是否一个属性对应一个分词
			List<IcdDiseaseSymptomDescription> list = icdDiseaseSymptomDescriptionDao.retrieveDescriptionSplitList(id);
			for (IcdDiseaseSymptomDescription value : list) {
				String array = value.getArray();
				String partPattern = value.getPartPattern();
				if (StringUtils.isNotBlank(array) || StringUtils.isNotBlank(partPattern)) {
					if (array.split(",").length != partPattern.split(",").length) {
						ReturnCode rc = ReturnCode.DYNAMIC_DESC_EXCEPTION;
						rc.setDesc("该记录的分词,属性没有一一对应:" + array);
						return ReturnUtil.fail(rc);
					}
				}
			}

			icdDiseaseSymptomDescriptionDao.updateCheckFlag(id, "1");
			return ReturnUtil.success();
		} else {
			return ReturnUtil.fail(ReturnCode.DYNAMIC_DESC_EXCEPTION);
		}

	}

	public ReturnData changeArray(String id, String array, User user) {
		if (StringUtils.isNotBlank(id) && StringUtils.isNotBlank(array)) {
			String[] arrayAndPart = array.split("\\(");
			if (arrayAndPart.length == 2) {
				if (arrayAndPart[1].split("\\)").length != 1) {
					ReturnCode rc = ReturnCode.DYNAMIC_DESC_EXCEPTION;
					rc.setDesc("该记录格式有误");
					return ReturnUtil.fail(rc);
				}
				String arr = arrayAndPart[0].substring(arrayAndPart[0].indexOf(",") + 1).substring(0,
						arrayAndPart[0].lastIndexOf(",") - 1);
				String property = arrayAndPart[1].substring(arrayAndPart[1].indexOf(",") + 1).substring(0,
						arrayAndPart[1].lastIndexOf(",") - 1);
				String[] arrs = arr.split(",");
				String[] propertys = property.split(",");
				if (arr.split(",").length != property.split(",").length) {
					ReturnCode rc = ReturnCode.DYNAMIC_DESC_EXCEPTION;
					rc.setDesc("该记录格式有误");
					return ReturnUtil.fail(rc);
				} else {
					arr = "";
					for (String value : arrs) {
						if (StringUtils.isBlank(value)) {
							ReturnCode rc = ReturnCode.DYNAMIC_DESC_EXCEPTION;
							rc.setDesc("该记录格式有误");
							return ReturnUtil.fail(rc);
						}
						arr += ",";
						arr += value;
					}
					property = "";
					for (String value : propertys) {
						if (StringUtils.isBlank(value)) {
							ReturnCode rc = ReturnCode.DYNAMIC_DESC_EXCEPTION;
							rc.setDesc("该记录格式有误");
							return ReturnUtil.fail(rc);
						}
						property += ",";
						property += value;
					}

				}
				Map<String, Object> value = icdDiseaseSymptomDescriptionDao.retrieveSplitById(Long.parseLong(id));
				// 检查是否分词相同
				int count = icdDiseaseSymptomDescriptionDao.checkRepeat(arr + ",", property + ",", value.get("description_id")+"",id);
				if (count > 0) {
					ReturnCode rc = ReturnCode.DYNAMIC_DESC_EXCEPTION;
					rc.setDesc("分词有重复");
					return ReturnUtil.fail(rc);
				}
				icdDiseaseSymptomDescriptionDao.updateArray(id, arr + ",", property + ",", user.getUserId());

			} else {
				ReturnCode rc = ReturnCode.DYNAMIC_DESC_EXCEPTION;
				rc.setDesc("该记录格式有误");
				return ReturnUtil.fail(rc);
			}

			return ReturnUtil.success();
		} else if (StringUtils.isNotBlank(id) && StringUtils.isBlank(array)) {
			icdDiseaseSymptomDescriptionDao.deleteById(Long.parseLong(id));
			return ReturnUtil.success();
		} else {
			return ReturnUtil.fail(ReturnCode.DYNAMIC_DESC_EXCEPTION);
		}

	}

	public JSONObject httpPost(String urlStr, String contentStr) throws Exception {
		// 请求的webservice的url
		URL url = new URL(urlStr);
		// 创建http链接
		HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();

		// 设置请求的方法类型
		httpURLConnection.setRequestMethod("POST");

		// 设置请求的内容类型
		httpURLConnection.setRequestProperty("Content-type", "application/x-www-form-urlencoded");

		// 设置发送数据
		httpURLConnection.setDoOutput(true);
		// 设置接受数据
		httpURLConnection.setDoInput(true);

		// 发送数据,使用输出流
		OutputStream outputStream = httpURLConnection.getOutputStream();
		// 发送的soap协议的数据

		String content = "keyword=" + URLEncoder.encode(contentStr, "UTF-8");

		// 发送数据
		outputStream.write(content.getBytes());

		// 接收数据
		InputStream inputStream = httpURLConnection.getInputStream();

		// 定义字节数组
		byte[] b = new byte[1024];

		// 定义一个输出流存储接收到的数据
		ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

		// 开始接收数据
		int len = 0;
		while (true) {
			len = inputStream.read(b);
			if (len == -1) {
				// 数据读完
				break;
			}
			byteArrayOutputStream.write(b, 0, len);
		}

		// 从输出流中获取读取到数据(服务端返回的)
		String response = byteArrayOutputStream.toString();
		return JSONObject.fromObject(response);
	}

	public Map<String, String> getTextSplitWord(JSONObject json) {
		String arr = "";
		String part = "";
		JSONObject data = json.getJSONObject("data");
		JSONArray symptoms = data.getJSONArray("symptoms");
		for (int i = 0; i < symptoms.size(); i++) {
			JSONObject jsonobject = symptoms.getJSONObject(i);
			JSONArray structure = jsonobject.getJSONArray("structure");
			for (int j = 0; j < structure.size(); j++) {
				JSONObject jsonobject2 = structure.getJSONObject(j);
				arr += ",";
				arr += jsonobject2.get("element");
				part += ",";
				part += jsonobject2.get("attr");
			}
		}
		if (StringUtils.isNotBlank(arr)) {
			Map<String, String> rtn = new HashMap<>();
			rtn.put("arr", arr + ",");
			rtn.put("part", part + ",");
			return rtn;
		}
		return null;
	}

}
